let addressCheck = document.querySelector(".address-check>input");



let address = document.querySelector(".address-list>ul");

//新建地址
let name = document.querySelector(".add-name");
let addressContent = document.querySelector(".newaddresstable")
let province = document.querySelector(".add-province");
let city = document.querySelector(".add-city");
let district = document.querySelector(".add-district");
let streetname = document.querySelector(".add-streetname");
let phone = document.querySelector(".add-tel");
let baoc = document.querySelector(".baoc");
//是否为编辑
let isEdit = '';
let pricesumAll = 0;	 
//支付按钮
let pay = document.querySelector(".jeisuan");
console.log(pay);

 (function(){
	 
	 addressCheck.onchange = function(){
	 	  // console.log(this.checked)
	 	  if(this.checked){
	 		  addressContent.style.display = "block";
	 	  }else{
	 		  addressContent.style.display = "none";
	 	  }
	 }
	
	function Data(msg,obj,data = {}){
		json.get(URL + '/api_country', data, even =>{
			// console.log(even);
			if(even.code != 0){
				console.log(even);
				return;
			};	
			
			let str = `	<option>${msg}</option>`;
			(even.data.area || even.data).forEach(item => {
				str += `<option value = ${item.name}>${item.name}</option>`;
				
			});
			obj.innerHTML = str;
			
		});
	};
	
	
	Data("所在省份",province);
	
	province.onchange = function(){
	
		Data("所在城市",city,{province : this.value});
	}
	city.onchange = function(){
	
		Data("所在区",district,{province : province.value, city : this.value});
	}
	
	product()
	
	
	
	 
	
	// addressList()
 })();
 
 
baoc.onclick = function(){
	console.log(name.value, streetname,phone.value)
	if(name.value == "" || streetname.value == "" || phone.value ==""){
		alert('姓名 地址 手机号不能为空');
		return;
	}
	// if(name.value == "" || )
	//验证
	if(isEdit){
		// 先删除，再保存
		json.post(URL + '/api_address', {
			status : 'deleteAddress',
			userId : TOKEN,
			addressId : isEdit
		}, even => {
			// console.log(res);
			if(even.code != 0){
				console.log(even);
				return;
			};
			//删除成功，再保存			
			createAddress();
		})
	}else{
		//调用新增方法
		 createAddress();
	}
	
	function createAddress(){
		json.post(URL + '/api_address', {
			status : 'addAddress',	
			userId : TOKEN,
			province : province.value,
			city : city.value,
			district : district.value,
			streetname : streetname.value,
			takename : name.value,
			tel: phone.value
		}, even =>{
			console.log(even);
			if(even.code != 0){
				console.log(even);
				return;
			};
			 addressList()
			name.value = '';
			phone.value = '';
			streetname.value = '';
		}); 
	};
};
//渲染地址
function addressList(){
	json.post(URL + '/api_address', {
			status : 'getAddress',
			userId : TOKEN
		}, even =>{
			console.log(even);
			
			if(even.code != 0){
				console.log(even);
				return;
			};
			
			if(even.data.length  == 0){
				address.innerHTML = '<h3>暂无地址，快去添加新地址吧</h3>';
				return;
			}
			
			address.innerHTML = `
					
			`;
			even.data.forEach(item =>{
				let li = document.createElement('li');
			    li.innerHTML = `
				
					<div class="tle flex-row-between align-center">
						<span>${item.takename}</span>
						<span>${item.tel}</span>
					</div>
					<div class="con">
						<p>${item.province} ${item.city} ${item.district}</p>
						<p>${item.streetname}</p>
						<p></p>
					</div>
					
					<div class="opt flex-row-between">
						<div class ="default-btn" address-id="${item.address_id}">
						${item.isDefault ? '默认地址' : '设置为默认'}</div>
						
						<div>
						<span class="edit-btn" address-id="${item.address_id}">编辑</span>&nbsp;
						<span class ="del-btn" address-id="${item.address_id}">删除</span>
						</div>
					</div>
				
				`
				
				address.appendChild(li);
			});
			
			addressedit(even.data)
		});
};
addressList()

function addressedit(data){
	 
	 address.onclick = function(e){
		 // console.log( e.target.innerHTML.trim() =="设置为默认");
		 
		// console.log(e.target.parentNode.parentNode)
		 	if(e.target.className == 'default-btn' && e.target.innerHTML.trim() == '设置为默认'){
				console.log("这样");
				json.post(URL + `/api_address`,{
					status : 'defaultAddress',
					userId : TOKEN,
					addressId : e.target.getAttribute('address-id')
				},even =>{
					console.log(even);
					if(even.code != 0){
						console.log(even);
						return;
					};
					//调用地址渲染
					addressList();
				})
			};
			//删除地址
			// console.log(e.target.parentNode)
			if(e.target.className == 'del-btn'){
				//请求
				json.post(URL + '/api_address', {
					status : 'deleteAddress',
					userId : TOKEN,
					addressId : e.target.getAttribute('address-id')
				}, even => {
					// console.log(res);
					if(even.code != 0){
						console.log(even);
						return;
					};
					//操作DOM
					
					e.target.parentNode.parentNode.parentNode.remove();
				})
			};
			
			//编辑
			if(e.target.className == 'edit-btn'){
				let nowAddressId = e.target.getAttribute('address-id');
				//拿到当前地址的内容，设置到下面，还要发信号，这是编辑过来的			
				let [itemAddress] = data.filter(item => {
					return item.address_id == nowAddressId
				});
				//设置到下面
				name.value = itemAddress.takename;
				streetname.value = itemAddress.streetname;
				phone.value = itemAddress.tel;
				//设置信号，这是编辑过来的
				isEdit = itemAddress.address_id;
				
				console.log(isEdit)
			};
				
		 
	 }
 }
 //计算总价
function pricesum(){
 	//拿到被选中的商品
 	let productChack = document.querySelectorAll(`[data-goods = "check"]`);
 	
 	let priceAll = document.querySelector(".priceall span");
 	
 	let sum = 0;
 	productChack.forEach(item =>{
 		
 		let num = item.parentNode.nextElementSibling.nextElementSibling.children[1].innerHTML
 		
 		let price = item.parentNode.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML;
 		
 		sum += num * price;
 	});
 	
 	priceAll.innerHTML = sum;
	
	pricesumAll = sum;
	
	
    return sum;
 }
 
 // 渲染订单
function product(){
	let carTable = document.querySelector(".cartable");
	
	//渲染
	json.post(URL + '/api_settlement', {
		status : 'getsettlement',
		userId: TOKEN,
		},even =>{
		    console.log(even)
			if(even.code != 0){
				console.log(even);
				return;
			};
			
			//验证是否有商品
			let {data} = even; // res.data;
			if(data.length == 0){
				carTable.innerHTML = '<tr>您的车车空空如也~~~</tr>';
				return;
			};
			
			let str = `
				<tr class="top" >
						<td width="120">
							
						</td>
						<td width="310">良品</td>
						<td width="130">数量</td>
						<td width="170">单价(元)</td>
						<td width="170">小计(元)</td>
						<td width="">操作</td>
					</tr>
			`;
			
			data.forEach(item =>{
				str +=`
				<tr class="list" >
					<td clas="flex-row-center" width="120">
						<div data-goods = "check"></div>
						<a><img src="${item.goods_thumb}"></a>
						</td>
					<td width="310">${item.goods_name}</td>
					<td width="130">
					<span  class="reduce" goods-id="${item.goods_id}" price="${item.price}" >-</span>
					&nbsp;<span>${item.goods_number}</span>&nbsp;
					<span class="add" goods-id="${item.goods_id}" price="${item.price}">+</span></td>
					</td>
					<td class="price" width="170">${item.price}</td>
					<td class="subtotal" width="170">${(item.price * parseInt(item.goods_number)).toFixed(2)}</th>
					<td class="del-btn" width=""  goods-id="${item.goods_id}"></td>
				</tr>
				
				`;
			});
			carTable.innerHTML = str;
			 pricesum()
			 console.log(pricesumAll)
			 //点击结算
			 pay.onclick = function(){
			 		 json.post(URL + '/api_payment', {
			 				userId : TOKEN,
			 				orderId : new Date().getTime(),
			 				returnUrl: 'http://127.0.0.1:8848/%E8%89%AF%E4%BB%93/myproduct.html',
			 				totalAmount: pricesumAll,
			 				subject: '订单标题',
			 				body: '订单详情',
			 			}, even =>{
			 				console.log(even);
			 				if(even.code != 0) return;
							console.log(even);
			 				location.href = even.data;
			 		})
			 }
		})
	
	
	// carTable.onclick = function(e){
		
		
	// 	let nowClassName = e.target.className;
	// 	console.log(nowClassName);
		
	// 	//点击+
	// 	if(nowClassName == 'add'){
	// 		let nowNumber = parseInt(e.target.previousElementSibling.innerHTML);
	// 		if(nowNumber >= 10) return;
			
	// 		nowNumber = ++nowNumber >= 10 ? 10 : nowNumber;
			
	// 		json.post(URL + `/api_cart`,{
	// 			status : 'addcart',
	// 			userId : TOKEN,
	// 			goodsId : e.target.getAttribute('goods-id'),
	// 			goodsNumber : nowNumber,
	// 		},even =>{
	// 			console.log(even)
	// 			if(even.code != 0) return;
				
	// 			e.target.previousElementSibling.innerHTML = nowNumber;
			
	// 			e.target.parentNode.nextElementSibling.nextElementSibling.innerHTML = e.target.getAttribute('price')*nowNumber
			
	// 			pricesum()
	// 		})
	// 	}
		
	// 	//点击-
	// 	if(nowClassName == 'reduce'){
	// 		let nowNumber = parseInt(e.target.nextElementSibling.innerHTML);
	// 		if(nowNumber <= 1) return;
			
	// 		nowNumber = --nowNumber <= 1 ? 1 : nowNumber;
			
	// 		json.post(URL + `/api_cart`,{
	// 			status : 'addcart',
	// 			userId : TOKEN,
	// 			goodsId : e.target.getAttribute('goods-id'),
	// 			goodsNumber : nowNumber,
	// 		},even =>{
	// 			console.log(even)
	// 			if(even.code != 0) return;
				
	// 			 e.target.nextElementSibling.innerHTML = nowNumber;
			
	// 			e.target.parentNode.nextElementSibling.nextElementSibling.innerHTML = e.target.getAttribute('price')*nowNumber
			
	// 			pricesum()
	// 		})
	// 	}
	// 	//点击删除
	// 	if(nowClassName == 'del-btn'){
		
	// 		json.post(URL + "/api_cart",{
	// 			status : 'delcart',
	// 			userId : TOKEN,
	// 			goodsId : e.target.getAttribute('goods-id')
	// 		},even =>{
				
	// 			if(even.code != 0) return;
				
	// 		    e.target.parentNode.remove();
				
	// 			pricesum();
				
	// 			carlist();
				
				
	// 		})
	// 	}
		
		
	// }
	
	
	
}